package com.powernode.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powernode.constant.BusinessEnum;
import com.powernode.domain.IndexImg;
import com.powernode.domain.Prod;
import com.powernode.exception.BusinessException;
import com.powernode.feign.StoreProdFeign;
import com.powernode.mapper.IndexImgMapper;
import com.powernode.model.Result;
import com.powernode.service.IndexImgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class IndexImgServiceImpl extends ServiceImpl<IndexImgMapper, IndexImg> implements IndexImgService {
    @Autowired
    private IndexImgMapper indexImgMapper;
    @Autowired
    private StoreProdFeign storeProdFeign;

    @Override
    public boolean saveIndexImg(IndexImg indexImage) {
        indexImage.setShopId(1L);
        indexImage.setCreateTime(new Date());
        Integer indexImageType = indexImage.getType();
        if (indexImageType == -1) {
            // 未关联商品
            indexImage.setProdId(-1L);
        }
        return indexImgMapper.insert(indexImage) > 0;
    }

    /** 根据id查询轮播图信息 用到远程调用
     * @param imgId
     * @return
     */
    @Override
    public IndexImg getInfoById(Long imgId) {
        // 根据id查询 轮播图的信息
        IndexImg indexImg = indexImgMapper.selectById(imgId);
        // 获取轮播图的关联类型
        if (indexImg.getType() == -1) {
            // 未关联商品
            indexImg.setProdName("未关联商品");
        } else {
            //  查询出关联的 商品信息  远程调用 feign 远程调用
            Result<List<Prod>> prodListByIds = storeProdFeign.getProdListByIds(CollectionUtil.toList(indexImg.getProdId()));
            // 判断是否调用成功
            if (BusinessEnum.OPERATION_FAIL.getCode().equals(prodListByIds.getCode())) {
                // 操作失败
                throw new BusinessException(prodListByIds.getMsg());
            }
            // 获取数据
            if (CollectionUtil.isNotEmpty(prodListByIds.getData())) {
                // 给轮播图里面的商品名称赋值
                indexImg.setProdName(prodListByIds.getData().get(0).getProdName());
                // 给轮播图里面的图片赋值
                indexImg.setPic(prodListByIds.getData().get(0).getPic());
            }
        }
        return indexImg;
    }

    /**
     * 修改轮播图
     * @param indexImage
     * @return
     */
    @Override
    public boolean modifyIndexImg(IndexImg indexImage) {
        return indexImgMapper.updateById(indexImage) > 0;
    }

    /**
     * 批量删除轮播图
     * @param imgIds 轮播图id集合
     * @return
     */
    @Override
    public boolean deleteIndexImageByIds(List<Long> imgIds) {
        if (CollectionUtil.isNotEmpty(imgIds)) {
            return indexImgMapper.deleteBatchIds(imgIds) > 0;
        }
        return false;
    }
}